﻿
//Ajax call Method for New Click.
// In this focus out from the previously selected row by calling function RowFocusOut.IF the status returned by this function is true then function tab initiate with last selected id 0 to form tabs
// uncheck all rows if checked, remove selection from last selected row and disable new button.
function GdNewClick(pModuleName) {
    var bStatus = false;
    //Focus out from the previously selected row by calling function RowFocusOut.IF the status returned by this function is true then function tab initiate with last selected id 0 to form tabs
    bStatus = RowFocusOut();

    if (bStatus) {

        //uncheck all the rows.
        UnCheckAllRows();

        //Remove the Selected row style from the selected row.
        RemoveSelectedStyleToRow();

        // Disable the Save Button.
        //$("#btn-Save-id").addClass("gd-disabled-cls");
        // Disable the New Button.
        $("#gd-new-id").addClass("gd-disabled-cls");
        // disable the set hardlock button
        $(".gb-hardlock-cls").attr("disabled", true).addClass("gb-hardlock-disable-cls");

        if (GdDestroy(true)) {

            GdDetails(pModuleName, 0);
        }

        // Set Values to globals for later use.
        SetGridVariables(strModuleName, 0, nGBTabIndex, strGbSortOn, strGbSortType, nGbCurrentPage, nGbOrgId);
    }
    return bStatus;
}

function GdSave(pModuleName, objGUser) {
    //if(fourmIsValid())
    {
        var temp = JSON.stringify(objGUser);
        
        $.ajax({
            type: 'POST',
            url: "/" + strModuleName + "/Save",
            data: '{ ' + pModuleName[pModuleName.length - 1] + ': ' + temp + '}',
            async: false,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (mydata) {
                //alert(mydata.Status.Success);
                if (mydata) {
                    if (mydata.Status.Success) {
                        //alert();
                        //call to refresh the grid,
                        GdRefresh(strModuleName, nGbCurrentlySelectedRecord, nGBTabIndex, strGbSortOn, strGbSortType, nGbCurrentPage, nGBPageSize, nGbOrgId, false);
                    }
                }
            }
        });
    }
}

//this method is used to call detail section
//*pModuleName - is used for module name
//* pRecordNo - is used for Record id.
function GdDetails(pModuleName, pRecordNo) {

    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/GetDetails",
        data: { pnId: pRecordNo },
        success: function (mydata) {

            if (pRecordNo > 0) {
                $(".detail-section-td-cls").empty();
                $(".detail-section").addClass("gb-hidden-cls");
                $("#td-row-detail-" + pRecordNo).empty().append(mydata);
                $("#tr-row-detail-" + pRecordNo).removeClass("gb-hidden-cls");
            }
            else {
                //alert("else");
                $(".info-upper-part").empty().append("<div class ='dt-back-div-cls'><div class='box-icon'><span id='btn-back-to-list-id' class='Save cursor-pointer-cls'>Back to List</span></div></div><div class='dt-control-div-cls' style='background-color:#D8E1E7' >" + mydata + "</div>");
            }

            // Disable the Save Button.

            $(".dt-save-cls").removeClass("gb-hidden-cls");

            //$("#btn-Save-id").addClass("gd-disabled-cls");
        }
    });



}

//this method is used to delete records from grid. this is called when we click delete button in delelete-confirm dialog
//in this function, in case of success we check for the deleted ids if currently seleted id is deleted then refresh grid acc to page no else acc to selected record.
// in case of false status show the message in ui and call the detail section because it was destroyed.
function GdDelete(pModuleName, pRecordNos) {
    pRecordNos = pRecordNos.toString();
    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/DeleteRecords",
        data: { pstrIds: pRecordNos },
        success: function (mydata) {
            //check for the returned status from controller
            if (mydata.Success == true) {
                //hide error msg div
                $("#div-dt-error-id").hide();
                //check for the deleted ids if currently seleted id is deleted then set currently seleted id to -1 so that refresh grid acc to page no. 
                var strDeletedRowId = pRecordNos.split(",");
                for (var i = 0; i < strDeletedRowId.length; i++) {
                    if (strDeletedRowId[i] == nGbCurrentlySelectedRecord) {
                        nGbCurrentlySelectedRecord = -1;
                    }
                }

                //call to refresh the grid,
                GdRefresh(strModuleName, nGbCurrentlySelectedRecord, nGBTabIndex, strGbSortOn, strGbSortType, nGbCurrentPage, nGBPageSize, nGbOrgId, false);

            }
                //if false status returned then show the status mesage and detail view.
            else {
                //call to refresh the grid,
                GdRefresh(strModuleName, nGbCurrentlySelectedRecord, nGBTabIndex, strGbSortOn, strGbSortType, nGbCurrentPage, nGBPageSize, nGbOrgId, false);

                CheckStatusDetails(mydata.StatusDetails, 'gd-error-message-display');
            }
        }
    });

}

//Ajax call Methods for copy.
function GdCopy(pModuleName, pRecordNos) {

    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/Copy",
        data: { pstrIds: pRecordNos },
        success: function (mydata) {


        }
    });
}

//Ajax call Methods for Paste.
function GdPaste(pModuleName, pRecordNos) {

    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/Paste",
        data: { pstrIds: pRecordNos },
        success: function (mydata) {


        }
    });
}



//this function is used in success of GDrefresh and GDInitiate
//in this we read the returned data acc to status of that set the grid variables and call row focus in event.
function Refresh(mydata, pModuleName, pRecordNo, pTabIndex, pSortOn, pSortType, pPageNo, pOrgId, pIsDetailTrue) {
    // Set Values to globals for later use.
    SetGridVariables(pModuleName, pRecordNo, pTabIndex, pSortOn, pSortType, pPageNo, pOrgId);
    //check if mydata contains status object then check if status is false then show error on ui
    if (mydata.Status) {

        if (mydata.Status.Success != true) {
            // here we will right error display code
        }
    }
        //else my data will contain returned html then we call row focus in event of selected row.
    else {
        $("#gd-error-message-display").hide();
        // in case of no error RowFocusIn event is fired.
        pRecordNo = RowFocusIn(pModuleName, pRecordNo, mydata, pIsDetailTrue);
        // Set Values to globals for later use. call to update selected row id.
        SetGridVariables(pModuleName, pRecordNo, pTabIndex, pSortOn, pSortType, nGbCurrentPage, pOrgId);
    }
}

//this function is used to destroy the dialogs of grid in case of grid destroy.
function GdDestroyGdDialogs() {
    //destroy delete  dialog

    //$("#dialog-delete-confirm").dialog("destroy");
    //$("#dialog-delete-confirm").remove();

}

//Methods for Grid Destroy.
function GdDestroy(bReleaseLock) {

    if (document.getElementById("txtsearchvalue")) {
        nGBSearch = $("#txtsearchvalue").val();
    }
    else {
        nGBSearch = '';
    }
    if (document.getElementById("selsearchon")) {
        nGBSearchOn = $("#selsearchon").val();
    }
    else {
        nGBSearchOn = '';
    }


    var ReleaseLockResult = true;
    if (bReleaseLock == true) {
        ReleaseLockResult = GdReleaseSoftLock(strModuleName, nGbCurrentlySelectedRecord);
    }

    //destroy dialogs of grid.
    GdDestroyGdDialogs();
    // empty the grid.

    nGBPageSize = parseInt($("#sl-gd-page-size-id").val());

    $(".info-upper-part").empty();

    return true;
}

//this function is used to refresh the grid
// in this we get refreshed data from controller then we laod data in grid 
//in this we also set variables of grid and call row focus in event of selected row
function GdRefresh(pModuleName, pRecordNo, pTabIndex, pSortOn, pSortType, pPageNo, pPageSize, pOrgId, pIsDetailTrue) {

    if (document.getElementById("txtsearchvalue")) {
        nGBSearch = $("#txtsearchvalue").val();
    }
    else {
        nGBSearch = '';
    }
    if (document.getElementById("selsearchon")) {
        nGBSearchOn = $("#selsearchon").val();
    }
    else {
        nGBSearchOn = '';
    }


    jQuery.ajaxSetup({ async: false, cache: false });
    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/GridRefresh",
        data: { pnId: pRecordNo, pstrSortOn: pSortOn, pstrSortType: pSortType, pnPageNo: pPageNo, pnPageSize: pPageSize, pstrSearch: nGBSearch, pstrSearchOn: nGBSearchOn, pnOrgId: pOrgId },
        success: function (mydata) {

            if (!mydata.Status) {

                jQuery.ajaxSetup({ async: true, cache: false });
                Refresh(mydata, pModuleName, pRecordNo, pTabIndex, pSortOn, pSortType, pPageNo, pOrgId, pIsDetailTrue);
            }
            else {

                var bSessionExist = CheckSessionState(mydata.Status);

                if (bSessionExist == false) {
                    window.location.replace("/");
                }
            }
        }
    });
}

// check sesion state
function CheckSessionState(Status) {

    if (!Status.Success) {
        if (Status.StatusDetails == "No Session Exist.") {

            return false;
        }
    }
    return true;
}

//this funtion is used to set Hard lock on row.
function GdSetHardLock(pModuleName, pRecordNo) {

    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/SetHardLock",
        data: { pnId: pRecordNo },
        success: function (mydata) {
            //check for status returned if true then set images of locks in grid 
            if (mydata.Success == true) {
                //hide error msg div
                // Call GdRefresh to rebuild the Grid.
                GdRefresh(strModuleName, nGbCurrentlySelectedRecord, nGBTabIndex, strGbSortOn, strGbSortType, nGbCurrentPage, nGBPageSize, nGbOrgId, false);

            }
            else {
                //else show the error msg in detail.

            }

        }
    });

}

//this funtion is used to release soft lock on row.
function GdReleaseSoftLock(pModuleName, pRecordNo) {

    var bStatus = false;

    jQuery.ajaxSetup({ async: false, cache: false });
    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/ReleaseSoftLock",
        data: { pnId: pRecordNo },
        success: function (mydata) {

            jQuery.ajaxSetup({ async: true, cache: false });

            if (mydata.Success == true) {

                bStatus = true;

                //  we need to remove lock image also if release soft lock is success.

                $("#tr-row-" + pRecordNo).children(".gd-td-default-lock-cls").children("span").removeClass("gd-softlock-by-owner-cls");
                $("#tr-row-" + pRecordNo).children(".gd-td-default-lock-cls").children("span").addClass("gd-default-lock-cls");

            }

            else {
                // show error something went wrong
                // if required
                //alert("Something Went wrong while release soft lock");
            }


        }
    });


    return bStatus;

}

//this funtion is used to release Hard lock on row.
function GdReleaseHardLock(pModuleName, pRecordNo) {
    $.ajax({
        type: 'POST',
        url: "/" + pModuleName + "/ReleaseHardLock",
        data: { pnId: pRecordNo },
        success: function (mydata) {
            if (mydata.Success == true) {
                // Call GdRefresh to rebuild the Grid.
                GdRefresh(strModuleName, nGbCurrentlySelectedRecord, nGBTabIndex, strGbSortOn, strGbSortType, nGbCurrentPage, nGBPageSize, nGbOrgId, false);

            }
            else {
                CheckStatusDetails(mydata.StatusDetails, "div-dt-error-id");

            }
        }
    });

}


function CheckStatusDetails(pstrMsg, pHtmlEleId) {

    $("#" + pHtmlEleId).show();

    $("#" + pHtmlEleId).empty().html(pstrMsg);
}

//this function is used to check all the rows in grid.
function CheckAllRows() {

    jQuery("#tbl-gd-main #0").addClass("first-row-cls");

    //bHeaderChecked contains whether header checkbox is clicked or not
    var bHeaderChecked = $("input:checkbox", "#grid-header-id").is(":Checked");

    var nCount = 0; // to store the count of no. of row checked.

    // if check box in header is checked,
    // then will check the all enabled rows(enabled means the rows that current user can delete.)
    // else disable the delete button.
    if (bHeaderChecked) {

        //this check all enabled check box ,Any disabled row will not be checked.
        $("tr:not('.first-row-cls') td:first-child input", "#tbl-gd-main").each(function (idx, ui) {
            if ($(ui).attr("type") == "checkbox") {
                if ($(ui).hasClass("gd-disabled-cls") == false) {
                    $(ui).prop('checked', true);
                    nCount = nCount + 1;

                }

            }
        });

        // if no. of rows checked greater than zero
        // then we will enable the delete button.

        if (nCount > 0) {
            $("#gd-delete-id").removeClass("gd-disabled-cls");
        }
    }
        // else case explained above( Disable the delete button).
    else {
        $("#gd-delete-id").addClass("gd-disabled-cls");
    }
}

//this function is used to uncheck all the rows in grid.
function UnCheckAllRows() {

    // Uncheck all check box of all the rows,if any.
    $(".chk-gd-row-cls").prop('checked', false);

    // Uncheck all check box of header,if any.
    $(".chk-gd-header-cls").prop('checked', false);

    //Disable the delete button.
    $("#gd-delete-id").addClass("gd-disabled-cls");

}

//this function is used to set selected row style to the currently selected row.
function SetSelectedStyleToRow(pRecordNo) {

    // remove the selected row class from grid ,if any
    RemoveSelectedStyleToRow();

    // add the selected row class to the given record.
    $("#tr-row-" + pRecordNo).addClass("selected-row-color-cls");

}

//this function is used to remove the selected row style to the currently selected row.
function RemoveSelectedStyleToRow() {

    // remove the selected row class from grid ,if any

    $(".tr-gd-row-cls").removeClass("td-gb-color-default-cls").removeClass("selected-row-color-cls");

}

//this function is used to remove focus from row of grid
//in this first we destroy detail section
//after that we check if currently selectrd row is softlocked by own then remove its soft lock.
//** pbIsRefreshCall- parameter contains information that refresh function is called after rowfocus out or not.
function RowFocusOut() {

    var bStatus = true;
    if (nGbCurrentlySelectedRecord > 0) {

        // check if given record is softlocked by current user or not.
        // we will call GdReleaseSoftLock only if it is already softlocked.
        if ($("#tr-row-" + nGbCurrentlySelectedRecord).children(".gd-td-default-lock-cls").children("span").hasClass("gd-softlock-by-owner-cls")) {

            // release the softlock according to Modulename and record no.
            bStatus = GdReleaseSoftLock(strModuleName, nGbCurrentlySelectedRecord);

        }
    }
    //GridUnLoad function call
    return bStatus;

}

// render the new html
// parameter pGrid cantains the html of the grid.
function GridLoad(pGrid) {

    // Append the grid html.
    $(".info-upper-part").empty().append(pGrid);
    $("img", ".logo-image-cls").attr("src", "Images/" + strModuleName + "-logo.png");

}



// set softlock call detail of selected row.
// parameter pGrid cantains the html of the grid.
function RowFocusIn(pModuleName, pRecordNo, pGrid, pIsDetailTrue) {

    // append the grid.
    // when grid is append then get selected row record no.
    $.when(GridLoad(pGrid)).done(function () {
    }).then(function () {
        //get id of row to be selected.
        pRecordNo = GetSelectedRow(pRecordNo);

        // Function used the Check the SoftLock and HardLock for Currntly Sected Row.
        currentRowLockSelect(pRecordNo);

        //set the style of selected row
        SetSelectedStyleToRow(pRecordNo);

        if (pIsDetailTrue) {
            // call gd details for details
            GdDetails(pModuleName, pRecordNo);
        }

    });
    return pRecordNo;
}

/* Function is Used to Add and Remove Classes and properties depending upon the current state of Row */
/* Classes used : 
    ".gd-td-default-lock-cls"   : Default Class used for row that contains no image of any HardLock or SoftLock.
    "gd-hardlock-by-owner-cls"  : This Class applies the image of Hardlock applied by current user in rows.
    "gd-hardlock-img-cls"       : This Class applies the image of Hardlock applied by other user in rows.
    "gd-softlock-img-cls"       : This Class applies the image of Softlock applied by other user in rows.
    ".gb-hardlock-cls"          : This Class id applied to the div in Detail Section that contains the set and release Hardlock icon.
    "gb-set-hardlock-cls"       : Include the image of icon in detail section when no Hardlock is applied on currently selected row. 
    "gb-release-hardlock-cls"   : Include the image of icon in detail section when Hardlock is applied on currently selected row.
*/

function currentRowLockSelect(pRecordNo) {
    // This Condition Checks Wheather Hardlock is applied by Current user or Another user.
    if ($("#tr-row-" + pRecordNo).children(".gd-td-default-lock-cls").children("span").hasClass("gd-hardlock-by-owner-cls") || $("#tr-row-" + pRecordNo).children(".gd-td-default-lock-cls").children("span").hasClass("gd-hardlock-img-cls")) {
        // If Condition Satisfies then "gb-set-hardlock-cls" is removed from Span and "gb-release-hardlock-cls" is applied (this span is Contained in div in Detail Section having Class "gb-hardlock-cls").
        $(".gb-hardlock-cls").children("span").removeClass("gb-set-hardlock-cls").addClass("gb-release-hardlock-cls");
        // Further Condition is Checked wheather Hardlock is Applied by another User then this is Satisfied.
        if ($("#tr-row-" + pRecordNo).children(".gd-td-default-lock-cls").children("span").hasClass("gd-hardlock-img-cls")) {
            // If Condition Satisfied the Disable Class And Attributes are given to the Save And Hardlock Image Above Detail Section.
            $(".gb-hardlock-cls").attr("disabled", true).addClass("gb-hardlock-disable-cls");

        }
            // If Hardlock is done by Current user the Else will be Applicable.
        else {
            // If Condition Satisfied the Disable Class And Attributes are removed from Save And Hardlock Image Above Detail Section.
            $(".gb-hardlock-cls").attr("disabled", false).removeClass("gb-hardlock-disable-cls");
            $("#btn-Save-id").removeClass("gd-disabled-cls");
        }
    }
        // This Condition is Else Statement if no Hardlock is applied by Current user or Another user.
    else {
        // If Condition Satisfies then "gb-set-hardlock-cls" is added from Span and "gb-release-hardlock-cls" is removed (this span is Contained in div in Detail Section having Class "gb-hardlock-cls").
        $(".gb-hardlock-cls").children("span").removeClass("gb-release-hardlock-cls").addClass("gb-set-hardlock-cls");
        // Further Condition is Checked wheather Softlock is Applied by another User then this is Satisfied.
        if ($("#tr-row-" + pRecordNo).children(".gd-td-default-lock-cls").children("span").hasClass("gd-softlock-img-cls")) {
            // If Condition Satisfied the Disable Class And Attributes are given to the Save And Hardlock Image Above Detail Section.
            $(".gb-hardlock-cls").attr("disabled", true).addClass("gb-hardlock-disable-cls");
            $("#btn-Save-id").addClass("gd-disabled-cls");
        }
            // If Softlock is done by Current user the Else will be Applicable.
        else {
            // If Condition Satisfied the Disable Class And Attributes are removed from Save And Hardlock Image Above Detail Section.
            $(".gb-hardlock-cls").attr("disabled", false).removeClass("gb-hardlock-disable-cls");

        }
    }
}

//Get Selected Row. find out which row is to be selected in newly build Grid.
function GetSelectedRow(pRecordNo) {

    var bRecordExist = false;

    // find out record whether record exist in newly built grid or not.
    if (pRecordNo != -1 && $("#tbl-gd-main").children().children(".tr-gd-row-cls[id='tr-row-" + pRecordNo + "']").length > 0) {
        bRecordExist = true;
    }

    // if record not exist in newly build grid then set the selected record as first.
    if (pRecordNo == -1 || bRecordExist == false) {
        if ($("#tbl-gd-main").children().children(".tr-gd-row-cls").length == 0) {
            pRecordNo = 0;
            $("#gd-new-id").addClass("gd-disabled-cls");
        } else {
            pRecordNo = $("#tbl-gd-main").children().children(".tr-gd-row-cls").eq(0).attr("id").replace("tr-row-", "");
        }
    }
    nGbCurrentlySelectedRecord = pRecordNo;

    return pRecordNo;
}

// Set grid variables values.
function SetGridVariables(pModuleName, pRecordNo, pTabIndex, pSortOn, pSortType, pPageNo, pOrgId) {
    strModuleName = pModuleName;
    strGbSortOn = pSortOn;
    strGbSortType = pSortType;
    nGbCurrentlySelectedRecord = pRecordNo;
    nGbCurrentPage = pPageNo;
    nGBTabIndex = pTabIndex;
    nGbOrgId = pOrgId;
}

//this function Display Error Message.  
function DisplayErrorMsg(pErrorMsg) {
    $("#error-message-display").empty().append(pErrorMsg);
}



//extended functions for jquery.
jQuery.fn.extend({
    //**this function is used to get string containing comma separated strGbIds of elements which are checked.**//
    GetSelectedIds: function () {

        try {
            var strGbIds = "";
            var dil = "";

            $(":checked", $(this)).each(function (i, j) {
                if ($(this).attr("class") != "chk-gd-header-cls") {
                    strGbIds = strGbIds + dil + $(this).parent().parent().attr("id").replace("tr-row-", ""); dil = ",";
                }
            });

            return strGbIds;

            return this;
        }
        catch (err) {

        }
    },

    //GetDataIds function returns all ids of all of the rows
    GetDataIds: function () {
        try {
            var strGbIds = "";
            var dil = "";

            //this loop loops through every row of the grid and extracts its id,and makes them comma seperated
            $($(".tr-gd-row-cls")).each(function (i, j) {
                strGbIds = strGbIds + dil + $(this).attr("id").replace("tr-row-", "");
                dil = ",";
            });
            return strGbIds;
            return this;
        }
        catch (err) {
        }
    }
});